import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'react-redux';
import { Tabs, Button, Row, Col, Form, message } from 'antd';
import Base from './form/base';
import Flow from './flow/flow';
import services from '../../../services/api';
import useVariableData from '../../../hook/useVariableData';
import { USAGE_SCOPE_LIMIT, VARIABLE_TYPE } from '../../../utils/constant';
import { randomKey, isRepeatArr } from '../../../utils/utils';
import useActionsData from 'src/hook/useActionsData';
import useOperatorData from 'src/hook/useOperatorData';
import TemplateTips from '../StrategyTemplate/templateTips';
import { validateChallenge } from '../../../utils/json/index';
import { NODE } from 'src/components/Flow/utils/constants';
import Modal from '../../../components/Modal/index';
import { getComponent } from 'src/components/Flow/utils/component';
import ReturnVariables from './flow/returnVariables';
import PrepositionFrom from './flow/prepositionFrom';
import storage from '../../../utils/storage';
import './index.less';
import { debounce } from 'lodash';
//activeKey
const _TAB_KEYS = {
  _CONFIG: '_CONFIG',
  _PREPOSITION: 'preposition',
  _RETURN: 'return',
};

/**
 * @method StrategyAdd
 */

function StrategyAdd(props) {
  const [activeKey, setActiveKey] = useState(_TAB_KEYS._CONFIG);
  const [appId, setAppId] = useState('');
  const [eventId, setEventId] = useState('');
  const [detail, setDetail] = useState({});
  const [preFormList, setPreFormList] = useState([]); // 返回变量全部的列表
  const [returnResults, setReturnResults] = useState([]); // 返回变量全部的列表
  const [isReturned, setIsReturned] = useState(false); // 是否请求过返回变量接口
  const [returnVariable, setReturnVariable] = useState([]); // 选中的返回变量
  const [returnVariableData, setReturnVariableData] = useState([]); // 选中的返回变量
  const [isFromTemplate, setIsFromTemplate] = useState(false); // 是否来自模板新增策略
  const [conflictData, setConflictData] = useState([]); // 模板新增策略冲突数据
  const [uninitialized, setUninitialized] = useState([]); // 模板新增策略未初始化三方名单等
  const [addData, setAddData] = useState({}); // 添加数据
  const [isShowReast, setIsShowReast] = useState(false); // 是否显示显示冲突数据
  const [projectCode, setProjectCode] = useState('');
  const [flows, setFlows] = useState({
    nodes: [
      {
        ...getComponent(NODE._START),
        x: 300,
        y: 100,
        id: randomKey(),
      },
    ],
    edges: [],
  });
  const limitType = [
    VARIABLE_TYPE._FIELD,
    VARIABLE_TYPE._FEATURE,
    VARIABLE_TYPE._MODEL,
    VARIABLE_TYPE._NAMELIST,
    VARIABLE_TYPE._THIRD_FEATURE,
    VARIABLE_TYPE._STRATEGY,
    VARIABLE_TYPE._RISK_LEVEL,
    VARIABLE_TYPE._LITERAL,
  ];
  const variable = useVariableData({
    limitType: limitType,
    appId,
    eventId,
    codes: props.codes,
    projectCode: projectCode,
  });
  const actions = props.isImportant ? props.actions || [] : useActionsData(USAGE_SCOPE_LIMIT._STRATEGY); //获取动作函数的列表
  const operator = useOperatorData();

  const _flow = useRef(); //flow对象
  const _returns = useRef(); //返回变量对象

  useEffect(() => {
    if (props.actionType !== 'detail') {
      props.dispatch({ type: 'pageClose/waringAdd' });
    }
    return () => {
      if (props.actionType !== 'detail') {
        props.dispatch({ type: 'pageClose/waringReduce' });
      }
    };
  }, []);

  useEffect(() => {
    if (props.id) {
      getDetail(props.id, props.version);
    }
    if (storage.templateToStrategyId) {
      getFromTempalte(storage.templateToStrategyId);
      setIsFromTemplate(true);
    }
    if (props.value && Object.keys(props.value).length > 0) {
      setDetailData(props.value);
    }
    return componentWillUnmount;
  }, []);

  useEffect(() => {
    if (props.value && Object.keys(props.value).length > 0) {
      setDetailData(props.value);
    }
  }, [props.value]);
  useEffect(() => {
    if (isShowReast) {
      showTemplateTips();
      setIsShowReast(false);
    }
  }, [isShowReast]);
  // 组件销毁
  function componentWillUnmount() {
    storage.templateToStrategyId = '';
    setIsFromTemplate(false);
  }
  // 获取详情
  function getDetail(id, version) {
    const params = version ? { id: id, version } : { id: id };
    services.strategyFlow.queryOne(params).then((res) => {
      if (res.code === '0') {
        setDetailData(res.data);
        setProjectCode(res.data.projectCode);
      } else {
        message.error(res.msg);
      }
    });
  }
  // 获取详情
  function setAddTemplate(data) {
    Modal.close();
    setConflictData(data);
    submitTemplateData(addData, data);
    // setIsAdd(true);
  }
  // 显示模板新增策略有冲突显示
  function showTemplateTips(record) {
    Modal.open({
      title: '提示信息',
      width: '1000px',
      content: (
        <TemplateTips
          data={conflictData}
          insideData={uninitialized}
          setAddTemplate={setAddTemplate}
          closeModel={() => {
            Modal.close();
          }}
        />
      ),
      isOkBtn: false,
      isCancelBtn: false,
      ok: () => {
        Modal.close();
      },
    });
  }
  // 获取策略模板数据
  function getFromTempalte(id) {
    services.template.queryOne({ strategy_template_id: id }).then((res) => {
      if (!res.code) {
        const datas = res.data.content || {};
        setDetailData(datas);
      } else {
        message.error(res.msg);
      }
    });
  }
  // 设置detail数据
  function setDetailData(data) {
    data.config = JSON.parse(data.config);
    setDetail(data);
    setReturnVariableData(data.config.mode.return_variables);
    const selectVariable = data.config.mode.return_variables
      ? data.config.mode.return_variables.map((it) => it.code)
      : [];
    if (!data.config || !Object.keys(data.config).length) return;
    data.config.mode.flows.nodes = data.config.mode.flows.nodes.map((it) => {
      // 这里重组strategy的节点的 is_break
      if (it.id && data.is_break_group && data.is_break_group.includes(it.id)) {
        it.is_break = true;
      }
      return it;
    });
    setFlows(data.config.mode.flows);
    setReturnVariable(selectVariable);
  }

  // 返回
  function back() {
    props.history.push('/strategy/config/index');
  }

  function getFlowData() {
    const data = _flow.current.save();
    const start = data.nodes.find((item) => item.type === NODE._START);

    if (!start) {
      throw '请添加开始节点';
    }
    const startSource = data.edges.find((item) => item.source === start.id);
    // if (!startSource) {
    //   throw '请为开始节点连线';
    // }

    // 查找出挑战组节点的名称数组
    const _challengesNames = data.nodes.filter((item) => item.type === NODE._CHALLENGE).map((it) => it.name);
    //如果他们的长度不一样，则说明有重复的组名
    if (isRepeatArr(_challengesNames)) {
      throw '冠军挑战节点的名称重复!';
    }
    data.nodes.forEach((item) => {
      const edge = data.edges.find((it) => {
        return it.source === item.id || it.target === item.id;
      });
      if (!edge) {
        throw '请为未连线的节点连线';
      }
      if (item.type === NODE._CHALLENGE) {
        validateChallenge(item, (err) => message.warning(err));
      }

      // 节点，需要验证他下面是否有多条线，如果大于等于2条，则必须配置edges_configs
      const edges = data.edges.filter((it) => it.source === item.id);
      const { edge_configs = [] } = item;
      const configs = edge_configs.filter((it) => edges.some((edge) => edge.id === it.id));

      // 如果线大于两条，则需要验证必须配置分流条件
      if (edges.length >= 2) {
        // 如果configs的长度不等于edges的长度，则遍历edges，把没有配置的线高亮
        if (configs.length !== edges.length) {
          edges.forEach((it) => {
            if (!configs.some((config) => config.id === it.id)) {
              highLightEdge(it.id);
            }
          });
          throw `请配置${item.name}下的分流条件`;
        } else {
          // 如果如果edge_configs的长度大于edges的长度,则把过滤后的数据赋值给item.edge_config
          if (edge_configs.length > edges.length) {
            item.edge_configs = configs;
          }
        }

        // 如果只有一条线
      } else if (edges.length === 1) {
        const { id, source, target } = edges[0];
        // 如果configs为空，则需要默认给他添加上id,source,target，引擎需要。。。
        if (configs.length === 0) {
          item.edge_configs = [{ id: id, source: source, target: target }];
        } else {
          item.edge_configs = configs;
        }
      } else if (edges.length === 0) {
        item.edge_configs = [];
      }
    });
    return data;
  }
  // 高亮线
  function highLightEdge(id) {
    const edge = _flow.current.findById(id);
    _flow.current.setItemState(edge, 'warning', true);
  }

  function getValues() {
    return new Promise((resolve, reject) => {
      props.form.validateFields((err, values) => {
        console.log(values, 789);
        if (!err) {
          const flows = getFlowFinallyConfig();
          if (!flows) {
            reject();
          }
          const params = {};
          params.name = values.name;
          params.code = values.code;
          params.projectCode = values.projectCode;
          params.remark = values.remark;
          params.config = {
            mode: {
              flows,
            },
          };
          params.config = JSON.stringify(params.config);
          resolve(params);
        } else {
          reject();
        }
      });
    });
  }
  // 提交数据
  function submitTemplateData(value, conflict) {
    const params = {
      strategy_template_id: storage.templateToStrategyId,
      app_id: value.app_id,
      event_id: value.event_id,
      product_id: value.product_id,
      name: value.name,
      code: value.code,
      conflict: conflict || conflictData,
    };
    services.template.templateDataImport(params).then((res) => {
      if (!res.code) {
        message.success(res.msg);
        props.history.push('/strategy/config');
      } else {
        message.error(res.msg);
      }
    });
  }
  // 提交
  function handleSubmit(e, type) {
    e.preventDefault();
    getValues().then((params) => {
      params.config = JSON.parse(params.config);
      params.config.mode.return_variables = returnVariableData.map((it) => {
        return {
          code: it.code,
          name: it.name,
          var_type: it.type || it.var_type,
          data_type: it.dataType || it.dataType,
          output_key: it.output_key,
        };
      });
      console.log(111, params, e, _returns);
      // _returns.current.getValue((value) => {
      // });
      if (isFromTemplate) {
        testTemplateData(params);
        setAddData(params);
        return;
      }
      // params.config.mode.return_variables = returnVariable;
      params.projectCode = projectCode;
      if (props.actionType === 'update' && !props.localSubmit) {
        params.id = props.isAuditLog ? props.record.id : props.id;
        params.projectCode = detail.projectCode;
        setProjectCode(detail.projectCode);
      }
      params.config = JSON.stringify(params.config);
      if (!(props.actionType === 'copy' || props.actionType === 'add')) {
        delete params.code;
      }
      if (type === 'draft') return handleDraft(params);

      if (props.isAuditLog) params.is_audit_log = true; // 审核记录里重新编辑，后端不做比较
      const action = props.actionType === 'copy' || props.actionType === 'add' ? 'addWithVersion' : 'updateWithVersion';

      if (!props.localSubmit) {
        services.strategyFlow[action](params).then((res) => {
          if (res.code === '0') {
            message.success(res.msg);
            if (props.afterSubmit) {
              props.afterSubmit();
            } else {
              props.closeModal && props.closeModal();
              if (props.isAuditLog) return;
              props.history.push('/strategy/config/index');
            }
          } else {
            message.error(res.msg);
          }
        });
      } else {
        props.usePolicy(params);
      }
    });
  }
  function handleDraft(params) {
    const action = props.actionType === 'copy' || props.actionType === 'add' ? 'add' : 'update';
    services.strategyFlow[action](params).then((res) => {
      if (res.code === '0') {
        message.success(res.msg);
        if (props.afterSubmit) {
          props.afterSubmit();
        } else {
          props.closeModal && props.closeModal();
          if (props.isAuditLog) return;
          props.history.push('/strategy/config/index');
        }
      } else {
        message.error(res.msg);
      }
    });
  }
  // 是模板新增策略验证数据
  const testTemplateData = async (params) => {
    const { data, code, msg } = await services.template.templateConfirm({
      strategy_template_id: storage.templateToStrategyId,
      name: params.name,
      code: params.code,
      app_id: params.app_id,
      product_id: params.product_id,
      event_id: params.event_id,
      remark: params.remark,
      projectCode: params.projectCode,
    });
    // console.log('数据啊', conflict)
    if (code) {
      message.error(msg);
      return;
    }
    if (data.conflict.length || data.uninitialized.length) {
      setUninitialized(data.uninitialized);
      setConflictData(data.conflict);
      setIsShowReast(true);
    }
    if (!data.conflict.length && !data.uninitialized.length) {
      submitTemplateData(params);
    }
  };
  /**  获取流程策略最终的配置信息
   */
  function getFlowFinallyConfig() {
    const finallyConfig = {};
    try {
      const data = getFlowData();

      finallyConfig.edges = data.edges;
      finallyConfig.nodes = data.nodes;
      return finallyConfig;
    } catch (err) {
      message.warning(err);
      return false;
    } finally {
      console.log('heh');
    }
  }

  function handleRef(ref) {
    _flow.current = ref;
    props.onRef && props.onRef(_flow.current);
  }

  function handleChangeTab(key) {
    // 如果是返回变量
    if (key === _TAB_KEYS._RETURN) {
      // if (props.isImportant) {
      //   // 导入时用详情里得变量数据
      //   setReturnResults(detail.returns);
      //   setIsReturned(true);
      //   setActiveKey(key);
      // } else {
      getValues()
        .then((params) => {
          delete params.remark;
          services.strategyFlow.returns(params).then((res) => {
            if (res.code === '0') {
              setReturnResults(res.data);
              setIsReturned(true);
              setActiveKey(key);
            } else {
              message.error(res.msg);
            }
          });
        })
        .catch((err) => {});
      // }
    } else if (key === _TAB_KEYS._PREPOSITION) {
      getValues()
        .then((params) => {
          delete params.remark;
          services.strategyFlow.preFormList(params).then((res) => {
            if (res.code === '0') {
              setPreFormList(res.data);
              setActiveKey(key);
            } else {
              message.error(res.msg);
            }
          });
        })
        .catch((err) => {});
    } else {
      setActiveKey(key);
    }
  }

  function renderBaseSetting() {
    return (
      <>
        <div className='tantuer-field-area'>
          <div className='form-title'>基本信息</div>

          <Base
            {...props}
            // events={props.isImport ? [{ event_id: detail.event_id, event_name: detail.event_name }] : events}
            value={detail}
            isFromTemplate={isFromTemplate}
            actionType={props.actionType}
            localSubmit={props.localSubmit}
            onGetAppProductEventIds={({ appId, eventId, projectCode }) => {
              setAppId(appId);
              setEventId(eventId);
              setProjectCode(projectCode);
            }}
          />
        </div>
        {
          <div className='tantuer-field-area'>
            <div className='form-title'>配置策略</div>
            <Tabs style={{ width: '100%' }} activeKey={activeKey} onChange={(activeKey) => handleChangeTab(activeKey)}>
              <Tabs.TabPane tab={'策略配置'} key={_TAB_KEYS._CONFIG} forceRender={true}>
                <Flow
                  importData={
                    isFromTemplate || props.isImportant ? (Object.keys(detail) ? detail.components : []) : undefined
                  }
                  {...props}
                  appId={appId}
                  eventId={eventId}
                  variable={variable}
                  using_variables={detail.using_variables}
                  operator={operator}
                  key={eventId}
                  value={flows}
                  actions={actions}
                  limitType={limitType}
                  wp={props.wp}
                  onRef={(ref) => handleRef(ref)}
                  disabled={props.actionType === 'detail' || isFromTemplate}
                  graphicMode={props.actionType === 'detail' || isFromTemplate ? 'disabled' : 'default'}
                  strategy_flow_mode={props.codes && props.codes.mode}
                  localSubmit={props.localSubmit}
                  strategy_mode={(props.codes && props.codes.strategy_mode) || []}
                  projectCode={detail.projectCode || projectCode}
                  compareData={
                    (props.compareData &&
                      props.compareData.config &&
                      props.compareData.config.mode &&
                      props.compareData.config.mode.flows) ||
                    {}
                  }
                />
              </Tabs.TabPane>

              <Tabs.TabPane tab={'前置表单'} key={_TAB_KEYS._PREPOSITION} forceRender={true}>
                <PrepositionFrom {...props} value={preFormList} />
              </Tabs.TabPane>

              <Tabs.TabPane tab={'返回变量'} key={_TAB_KEYS._RETURN} forceRender={true}>
                <ReturnVariables
                  {...props}
                  returnResults={returnResults || []}
                  codes={(props.codes && props.codes.return_variable) || []}
                  value={returnVariable}
                  createRef={_returns}
                  onOkHandle={(val) => {
                    console.log(89, val);
                    setReturnVariableData(val);
                  }}
                  disabled={props.actionType === 'detail' || isFromTemplate}
                  isReturned={isReturned}
                />
              </Tabs.TabPane>
            </Tabs>
          </div>
        }
      </>
    );
  }

  return (
    <div className='stretegy-content'>
      <div className='stretegy-wp tantuer-form ' id='intro-farm' style={{ position: 'relative' }}>
        <Form onSubmit={() => false} autoComplete='off' className='stretegy-wp-form'>
          {renderBaseSetting()}

          <Row type='flex' justify='start' className='form-submit-area'>
            <Col>
              {props.actionType !== 'detail' && !props.changeMode && (
                <>
                  {!props.localSubmit ? (
                    <>
                      <Button type='primary' className='mr-15' onClick={debounce((e) => handleSubmit(e, 'test'), 300)}>
                        组件测试
                      </Button>
                      <Button type='primary' className='mr-15' onClick={debounce((e) => handleSubmit(e, 'draft'), 300)}>
                        保存草稿
                      </Button>
                      <Button
                        type='primary'
                        onClick={handleSubmit}
                        autoFocus={true}
                        data-intro='点击确认，流程编辑完毕，系统按照您设计的流程执行'
                        data-step='3'
                      >
                        确定
                      </Button>
                      <Button
                        style={{ marginLeft: '15px' }}
                        onClick={() => {
                          props.isAuditLog ? props.closeModal(true) : back();
                        }}
                      >
                        取消
                      </Button>
                    </>
                  ) : (
                    <>
                      <Button
                        type='primary'
                        onClick={handleSubmit}
                        autoFocus={true}
                        data-intro='点击确认，流程编辑完毕，系统按照您设计的流程执行'
                        data-step='3'
                      >
                        确定
                      </Button>
                      <Button style={{ marginLeft: '15px' }} onClick={() => props.closeModal()}>
                        取消
                      </Button>
                    </>
                  )}
                </>
              )}

              {props.changeMode &&
                (props.actionType !== 'detail' ? (
                  <>
                    <Button type='primary' autoFocus={true} onClick={handleSubmit}>
                      确定
                    </Button>
                    <Button className='marl10' onClick={props.cancelEdit}>
                      取消编辑
                    </Button>
                  </>
                ) : (
                  <>
                    <Button type='primary' onClick={props.startEdit}>
                      编辑
                    </Button>
                  </>
                ))}
            </Col>
          </Row>
        </Form>
      </div>
    </div>
  );
}
function mapStateToProps(state) {
  return {
    codes: {
      ...state.code,
    },
  };
}
export default connect(mapStateToProps)(Form.create()(StrategyAdd));
